import { useEffect, useState } from 'react';
import JsBarcode from 'jsbarcode';
import { PdfNodeFunc } from '../../../components';
import { NodeResizer, ResizeParams } from '@xyflow/react';
import { useRequest } from 'ahooks';
export const PdfBarcode: PdfNodeFunc = (node) => {
    const [dataUrl, setDataUrl] = useState('');
    const { data, selected } = node ?? {};
    const style = data?.style;
    const [width, setWidth] = useState(0);
    const [height, setHeight] = useState(0);
    const { run } = useRequest((params: ResizeParams) => {
        setWidth(params.width);
        setHeight(params.height);
        return Promise.resolve(true);
    }, {
        debounceWait: 50,
        manual: true
    });
    useEffect(() => {
        setWidth(node.width)
        setHeight(node.height)
    }, [node.width, node.height])
    useEffect(() => {
        const canvas = document.createElement('canvas');
        // 使用 JsBarcode 渲染条码到 Canvas
        JsBarcode(canvas, data?.value ?? '123456789012', {
            format: 'CODE128', // 条码格式
            lineColor: style?.color ?? '#000000', // 条码颜色
            width, // 条码宽度
            height, // 条码高度
            displayValue: true // 是否显示文本
        });
        // 获取 Base64 数据
        setDataUrl(canvas.toDataURL());
    }, [height, width, data?.value]);
    return (<>
        <NodeResizer
            color="#1890ff"
            isVisible={selected}
            onResize={(e: any, params: ResizeParams) => {
                run(params);
            }}
        />
        <img src={dataUrl}
            style={{ ...style,width, height }}></img>
    </>
    );
};
PdfBarcode.displayName = "Barcode";
/**
 * 默认值
 */
PdfBarcode.defaultProps = { width: 200, height: 50 };